/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.fuatnow.game.server;

import com.fuatnow.game.entity.User;
import com.fuatnow.game.handler.MsgHander;
import com.fuatnow.game.handler.RegisterHandler;
import com.fuatnow.game.work.Worker;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.CharsetUtil;

import java.util.List;
import java.util.Map;

import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * Outputs index page content.
 */
public class WebSocketIndexPageHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private final String websocketPath;
    private final String registerPath = "/register/";

    public WebSocketIndexPageHandler(String websocketPath) {
        this.websocketPath = websocketPath;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
        // Handle a bad request.
        if (!req.decoderResult().isSuccess()) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
            return;
        }

        // Allow only GET methods.
        if (req.method() != GET) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
            return;
        }

        String reqUri = req.uri();
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(reqUri);
        String path = queryStringDecoder.path();
        Map<String, List<String>> parameters = queryStringDecoder.parameters();

        // Send the index page
        if ("/".equals(reqUri) || "/index.html".equals(reqUri))
        {
            String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath);
            ByteBuf content = WebSocketServerIndexPage.getContent(webSocketLocation);
            FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
            res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
            HttpUtil.setContentLength(res, content.readableBytes());
            sendHttpResponse(ctx, req, res);
        }
        else if(this.registerPath.equals(path))
        {

            User reg = RegisterHandler.getRegUser(parameters);
            MsgHander mHdler = new RegisterHandler(ctx,req,reg);
            Worker.dispath(mHdler);
//            userInfo = new UserInfo(new dbExecuteStateListener(){
//                @Override
//                public void executeSuccess(String msg) {
//                    super.executeSuccess(msg);
//                    String sendMsg = MessageService.sendMessage(ProtocolConstant.REG_USER, "suc").toString();
//                    ByteBuf content = Unpooled.wrappedBuffer(sendMsg.getBytes());
//                    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK,content );
//                    res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
//                    HttpUtil.setContentLength(res, content.readableBytes());
//                    sendHttpResponse(userInfo.getCtx(), userInfo.getReq(), res);
//                }
//
//                @Override
//                public void executeFailed(int errorCode, String msg) {
//                    super.executeFailed(errorCode, msg);
//                    sendHttpResponse(userInfo.getCtx(), userInfo.getReq(), new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
//                }
//            });
//            UserInfo userInfo = new UserInfo();
//            userInfo.register(reg);
//            if(reg.getUsrID() != -1)
//            {
//                String sendMsg = MessageService.registerUser(ProtocolConstant.USER_REG, reg.getUsrID()).toString();
//                ByteBuf content = Unpooled.wrappedBuffer(sendMsg.getBytes());
//                FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK,content );
//                res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
//                HttpUtil.setContentLength(res, content.readableBytes());
//                sendHttpResponse(ctx, req, res);
//            }
//            else
//            {
//                sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
//            }
        }
        else if(this.websocketPath.equals(reqUri))
        {
            // Handshake
            String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath);
            WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(webSocketLocation, null, true);
            WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
            if (handshaker == null)
            {
                WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
            }
            else
            {
                 ChannelFuture channelFuture = handshaker.handshake(ctx.channel(), req);
                 System.out.println("handshaker success");
            }
        }
        else
        {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
    
    

    @Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.handlerAdded(ctx);
		Channel incoming = ctx.channel();
        System.out.println("收到" + incoming.remoteAddress() + " 握手请求");
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		Channel incoming = ctx.channel();
        System.out.println("收到" + incoming.remoteAddress() + " remove");
		super.handlerRemoved(ctx);
	}

	private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
        // Generate an error page if response getStatus code is not OK (200).
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
            HttpUtil.setContentLength(res, res.content().readableBytes());
        }

        // Send the response and close the connection if necessary.
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
        String protocol = "ws";
        if (cp.get(SslHandler.class) != null) {
            // SSL in use so use Secure WebSockets
            protocol = "wss";
        }
        return protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path;
    }
}

